﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;

namespace TanzimSaqib.NoBrainer.Sample.DataAccess
{
    public partial class LinqContext
    {
        private const string DEFAULT_CONNECTION_STRING_NAME = "NoBrainer.Sample";

        public LinqContext GetDbInstance()
        {
            return new LinqContext(ConfigurationManager.ConnectionStrings[DEFAULT_CONNECTION_STRING_NAME].ConnectionString);
        }

        public virtual T Insert<T>(T obj) where T : class
        {
            using (var db = GetDbInstance())
            {
                db.GetTable<T>().InsertOnSubmit(obj);
                db.SubmitChanges();
                return obj;
            }
        }

        public virtual T Insert<T>(Action<T> populate) where T : class, new()
        {
            return Insert(new T(), populate);
        }

        public virtual T Insert<T>(T obj, Action<T> populate) where T : class
        {
            populate(obj);
            return Insert(obj);
        }

        public virtual T Update<T>(T obj, Action<T> populate) where T : class
        {
            using (var db = GetDbInstance())
            {
                db.GetTable<T>().Attach(obj);
                populate(obj);
                db.SubmitChanges();
                return obj;
            }
        }

        public virtual T Update<T>(T obj) where T : class
        {
            using (var db = GetDbInstance())
            {
                db.GetTable<T>().Attach(obj);
                db.SubmitChanges();
                return obj;
            }
        }

        public virtual void Delete<T>(T obj, System.Data.Linq.DataContext db) where T : class
        {
            db.GetTable<T>().DeleteOnSubmit(obj);
            db.SubmitChanges();
        }
    }
}
